package com.example.book.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.*;

@RestController
public class FutureTaskController {

    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    @RequestMapping("/getDeferredResult")
    public DeferredResult<String> getSth() {
        DeferredResult deferredResult = new DeferredResult();

        executorService.submit(() -> {
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
            }
            // setResult是在子线程里调用!!!
            deferredResult.setResult("ABC");
        });

        deferredResult.onCompletion(()-> System.out.println("子线程也结束了。。"));
        return deferredResult;
    }

    @RequestMapping("/getFuture")
    public Future<String> getFuture() {
        // 必须是ListenableFuture的子类，或者CompletionStage子类，或者是DeferredResult 不能是FutureTask
        // 如何返回CompletableFuture
        // 不指定线程池时，任务默认使用的是java.util.concurrent.CompletableFuture.ASYNC_POOL ForkJoinPool
        CompletableFuture<String> ftu2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
            }
            return "getFuture";
        }, executorService);
        System.out.println(1);
//        Future<String> future = executorService.submit(() -> {  });
        return ftu2;
    }

    @RequestMapping("/getCallableStr")
    public Callable<String> getCallableStr() {
        //没有指定线程池，使用MyWebConfig中配置的线程池
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                }
                return "getCallableStr";
            }
        };
    }
}
